package client.view;

import java.awt.Color;
import java.awt.Component;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

import client.AccountProxy;
import client.LobbyClient;

/**
 * A graphical list of AccountProxyViews to visualize accounts connected to the master server
 */
public class AccountList extends JList {
	private DefaultListModel dlm;
	private LobbyClient client;
	private AccountProxy me;
	/**
	 * Creates a new AccountList for the given LobbyClient
	 */
	public AccountList(LobbyClient c, AccountProxy me) {
		System.out.println("al me is " + me);
		dlm = new DefaultListModel();
		this.me = me;
		this.setModel(dlm);
		this.setCellRenderer(new AccountListRenderer());
		this.client=c;
		for (AccountProxy a : client.getLoggedOn()) {
			addAccount(a);
		}
	}
	/**
	 * Adds a new AccountProxyView for the given AccountProxy to the list of accounts available
	 */
	public void addAccount(AccountProxy ap) {
		System.out.println("add account proxy view");
		dlm.addElement(new AccountProxyView(ap));
	}
	public void removeAccount(AccountProxy ap) {
		for (int i=0;i<dlm.getSize();i++) {
			AccountProxyView apv = (AccountProxyView)(dlm.getElementAt(i));
			if (apv.getAccountProxy().getUserName().equals(ap.getUserName())) { dlm.removeElement(apv); }
		}
	}
	/**
	 * Retrieves the selected AccountProxy in the list
	 */
	public AccountProxy getSelectedAccount() { return (AccountProxy)(this.getSelectedValue()); }
	
	private class AccountListRenderer implements ListCellRenderer {

		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean hasFocus) {
			AccountProxyView apv = (AccountProxyView)value;
			if (apv.getAccountProxy().getUserName().equals(me.getUserName())) {
				apv.setBackground(new Color(250,250,250));
				AccountList.this.clearSelection();
			}
			else if (isSelected) {
				apv.setBackground(list.getSelectionBackground());
				apv.setForeground(list.getSelectionForeground());
			} else {
				apv.setBackground(list.getBackground());
				apv.setForeground(list.getForeground());
			}
			return apv;
		}
	}
}
